package com.example.jnuexperiment2025;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.jnuexperiment2025.dataop.Book;

import java.util.List;

public class RecyclerViewBookAdpater extends RecyclerView.Adapter<RecyclerViewBookAdpater.ViewHolder> {

    private List<Book> mBookList;
    private OnItemActionCallback callback;

    public interface OnItemActionCallback {
        void onAddItem(int position);
        void onUpdateItem(int position);
        void onDeleteItem(int position);
    }

    public void setCallback(OnItemActionCallback callback) {
        this.callback = callback;
    }

    class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
        ImageView bookImage;
        TextView bookName;

        public ViewHolder(View view) {
            super(view);
            bookImage = view.findViewById(R.id.image_view_book_cover);
            bookName = view.findViewById(R.id.text_view_book_name);
            view.setOnCreateContextMenuListener(this);
        }

        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            menu.add(0, 0, 0, R.string.action_add).setOnMenuItemClickListener(item -> {
                if (callback != null) callback.onAddItem(getAdapterPosition());
                return true;
            });
            menu.add(0, 1, 0, R.string.action_update).setOnMenuItemClickListener(item -> {
                if (callback != null) callback.onUpdateItem(getAdapterPosition());
                return true;
            });
            menu.add(0, 2, 0, R.string.action_delete).setOnMenuItemClickListener(item -> {
                if (callback != null) callback.onDeleteItem(getAdapterPosition());
                return true;
            });
        }
    }

    public RecyclerViewBookAdpater(List<Book> bookList) {
        mBookList = bookList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_book, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Book book = mBookList.get(position);
        holder.bookImage.setImageResource(book.getCoverResourceId());
        holder.bookName.setText(book.getTitle());
    }

    @Override
    public int getItemCount() {
        return mBookList.size();
    }
}